package gwtgaetools.client;


import gwtgaetools.client.listeners.Listener;

import java.util.ArrayList;



public class ItemManager<Model> implements Listener<ItemManager<Model>> {

	public ArrayList<Listener<ItemManager<Model>>> listeners = new ArrayList<Listener<ItemManager<Model>>>();
	public ArrayList<Listener<Void>> voidListeners = new ArrayList<Listener<Void>>();
	
	private ItemManager<Model> om = this;
	
	private Model item;

	public ItemManager() {}
	
	public ItemManager(Model t) {
		setItem(t);
	}
	
	public ItemManager<Model> getOM() { 
		if (om == this) {
			return this;
		} else 
			return om.getOM();
	}
	
	public void setItem(Model t) {
		om = this;
		item = t;
		observe(this);
	}
	
	@SuppressWarnings("unchecked")
	public void setObservedManager(ItemManager<?> itemManager) {
		if (om != this)
			om.listeners.remove(this);	

		if (itemManager!=null) {
			
			// TODO: Is this necessary?
//			om = m.om;
			om = (ItemManager<Model>) itemManager;
			
			om.registerListener(this);
		}
		else {
			om = this;
			item = null;
			observe(this);
		}

	}
	
	public Model getItem() {
		if (om==this)
			return item;
		else
			return om.getItem();
	}
	
	@Override public void observe(ItemManager<Model> m) {
		for (Listener<ItemManager<Model>> l : listeners) {
			l.observe(m);
		}
		for (Listener<Void> l : voidListeners) {
			l.observe(null);
		}
	}
	
	public void registerListener(Listener<ItemManager<Model>> l) {
		registerListener(l, true);
	}
	
	public void registerListener(Listener<ItemManager<Model>> l, boolean SET_ITEM) {
		listeners.add(l);
		if (SET_ITEM)
			l.observe(this);
	}

	public void registerVoidListener(Listener<Void> l) {
		voidListeners.add(l);
		l.observe(null);
	}

	@Override public String toString() { return getItem().toString(); }
	
}
